/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mapbox.ohos.gestures;


import ohos.agp.window.service.WindowManager;
import ohos.app.Context;
import ohos.multimodalinput.event.TouchEvent;

import java.util.Set;

/**
 * Base class for all of the gesture detectors.
 *
 * @param <Listener> listener that will be called with gesture events/updates.
 */
public abstract class BaseGesture<Listener> {
    protected final Context context;
    protected final WindowManager windowManager;
    private final OhosGesturesManager gesturesManager;
    private TouchEvent currentEvent;
    private TouchEvent previousEvent;
    private long gestureDuration;
    private boolean isEnabled = true;

    /**
     * Listener that will be called with gesture events/updates.
     */
    protected Listener listener;

    /**
     * BaseGesture
     *
     * @param context
     * @param gesturesManager
     */
    public BaseGesture(Context context, OhosGesturesManager gesturesManager) {
        this.context = context;
        this.windowManager = WindowManager.getInstance();
        this.gesturesManager = gesturesManager;
    }

    /**
     * onTouchEvent
     *
     * @param motionEvent
     * @return boolean
     */
    protected boolean onTouchEvent(TouchEvent motionEvent) {
        return analyze(motionEvent);
    }

    private boolean analyze(TouchEvent motionEvent) {
        if (motionEvent == null) {
            return false;
        }

        if (previousEvent != null) {
            previousEvent = null;
        }
        if (currentEvent != null) {
            previousEvent = currentEvent;
            currentEvent = null;
        }
        currentEvent = motionEvent;
        gestureDuration = currentEvent.getOccurredTime() - currentEvent.getStartTime();

        return analyzeEvent(motionEvent);
    }

    /**
     * analyzeEvent
     *
     * @param motionEvent
     * @return boolean
     */
    protected abstract boolean analyzeEvent(TouchEvent motionEvent);

    /**
     * canExecute
     *
     * @param invokedGestureType
     * @return boolean
     */
    protected boolean canExecute(int invokedGestureType) {
        if (listener == null || !isEnabled) {
            return false;
        }

        for (Set<Integer> exclusives : gesturesManager.getMutuallyExclusiveGestures()) {
            if (exclusives.contains(invokedGestureType)) {
                for (int gestureType : exclusives) {
                    for (BaseGesture detector : gesturesManager.getDetectors()) {
                        if (detector instanceof ProgressiveGesture) {
                            ProgressiveGesture progressiveDetector = (ProgressiveGesture) detector;
                            if (progressiveDetector.getHandledTypes().contains(gestureType)
                                && progressiveDetector.isInProgress()) {
                                return false;
                            }
                        }
                    }
                }
            }
        }

        return true;
    }

    /**
     * setListener
     *
     * @param listener
     */
    protected void setListener(Listener listener) {
        this.listener = listener;
    }

    /**
     * removeListener
     */
    protected void removeListener() {
        listener = null;
    }

    /**
     * This is a duration of the user's total interaction with the touch screen,
     * accounting for the time before the gesture was recognized by the detector.
     *
     * @return duration of the gesture in millis.
     */
    public long getGestureDuration() {
        return gestureDuration;
    }

    /**
     * Returns most recent event in this gesture chain.
     *
     * @return most recent event
     */
    public TouchEvent getCurrentEvent() {
        return currentEvent;
    }

    /**
     * Returns previous event in this gesture chain.
     *
     * @return previous event
     */
    public TouchEvent getPreviousEvent() {
        return previousEvent;
    }

    /**
     * Check whether this detector accepts and analyzes motion events. Default is true.
     *
     * @return true if it analyzes, false otherwise
     */
    public boolean isEnabled() {
        return isEnabled;
    }

    /**
     * Set whether this detector should accept and analyze motion events. Default is true.
     *
     * @param enabled true if it should analyze, false otherwise
     */
    public void setEnabled(boolean enabled) {
        isEnabled = enabled;
    }
}
